//Date: 2023-11-12 22:37:37
//LastEditors: jie zhengjie_liang@qq.com
//LastEditTime: 2023-12-11 22:30:48
//FilePath: /dimlight/main/service/guid_service.go

package service

import (
	"math/rand"
	"strconv"
	"strings"
	"sync"
	"time"
)

func GetGuidForLink() string {
	return generateRandondCodeID(4)
}

var (
	rng         *rand.Rand
	rngSyncOnce sync.Once
	charset     = "012345678"
)

func generateRandomString(length int) string {
	rngSyncOnce.Do(func() {
		// 创建一个本地随机数生成器
		rng = rand.New(rand.NewSource(time.Now().UnixNano()))
	})

	result := make([]byte, length)
	for i := 0; i < length; i++ {
		randomIndex := rng.Intn(len(charset))
		result[i] = charset[randomIndex]
	}

	return string(result)
}

var (
	generateRandondCodeIDrng         *rand.Rand
	generateRandondCodeIDrngSyncOnce sync.Once
)

func generateRandondCodeID(n int) string {
	generateRandondCodeIDrngSyncOnce.Do(func() {
		// 创建一个本地随机数生成器
		generateRandondCodeIDrng = rand.New(rand.NewSource(time.Now().UnixNano()))
	})

	// 创建一个包含所有可能数字的slice
	numbers := make([]int8, 10)
	for i := range numbers {
		numbers[i] = int8(i)
	}

	// 打乱slice

	generateRandondCodeIDrng.Shuffle(len(numbers), func(i, j int) {
		numbers[i], numbers[j] = numbers[j], numbers[i]
	})

	return buildStringFromIntArr(numbers[:n])
}

func buildStringFromIntArr(source []int8) string {
	// 使用strings.Builder来高效拼接字符串
	var builder strings.Builder

	// 遍历整数数组
	for _, num := range source {
		// 将整数转换为字符串并追加到builder中
		builder.WriteString(strconv.Itoa(int(num)))
	}

	// 获取最终拼接的字符串
	result := builder.String()

	return result
}
